package com.yunhe.policyfulfillment.policyful.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.model.mybatis.PageResult;
import com.yunhe.common.util.StringUtil;
import com.yunhe.policyfulfillment.authority.domain.PolicyCompanyUser;
import com.yunhe.policyfulfillment.authority.domain.PolicyOrg;
import com.yunhe.policyfulfillment.authority.domain.PolicyUser;
import com.yunhe.policyfulfillment.authority.model.LoginUserApplyMatterQueryCondition;
import com.yunhe.policyfulfillment.authority.model.SupplementaryMaterials;
import com.yunhe.policyfulfillment.authority.repository.IPolicyOrgRepository;
import com.yunhe.policyfulfillment.authority.repository.PolicyCompanyUserRepository;
import com.yunhe.policyfulfillment.authority.service.IPolicyUserService;
import com.yunhe.policyfulfillment.constant.PolicyFulfillmentConstant;
import com.yunhe.policyfulfillment.policyful.domain.*;
import com.yunhe.policyfulfillment.policyful.model.*;
import com.yunhe.policyfulfillment.policyful.repository.PolicyInfoApplyMaterialRepository;
import com.yunhe.policyfulfillment.policyful.repository.PolicyInfoApplyMatterRepository;
import com.yunhe.policyfulfillment.policyful.repository.PolicyInfoApproveProcessRepository;
import com.yunhe.policyfulfillment.policyful.service.IPolicyInfoMatterService;
import com.yunhe.policyfulfillment.policyful.service.PolicyInfoApplyMatterService;
import com.yunhe.policyfulfillment.policyful.service.SerialNumService;
import com.yunhe.policyfulfillment.util.BeansUtil;
import com.yunhe.policyfulfillment.util.MyHeaderUtil;
import com.yunhe.policyfulfillment.util.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yunhe.common.util.CollectionUtil;

import java.util.*;

/**
 * @description 政策兑现企业在线申请/审批事项
 * @author hetao
 * @date 2021-08-24
 */
@Service
@Slf4j
public class PolicyInfoApplyMatterServiceImpl implements PolicyInfoApplyMatterService {

    @Autowired
    private PolicyInfoApplyMatterRepository policyInfoApplyMatterRepository;

    @Autowired
    private IPolicyInfoMatterService policyInfoMatterService;

    @Autowired
    private PolicyInfoApplyMaterialRepository applyMaterialRepository;

    @Autowired
    private SerialNumService serialNumService;

    @Autowired
    private MyHeaderUtil myHeaderUtil;

    @Autowired
    private IPolicyOrgRepository policyOrgRepository;

    @Autowired
    private PolicyInfoApproveProcessRepository policyInfoApproveProcessRepository;

    @Autowired
    private PolicyCompanyUserRepository policyCompanyUserRepository;

    @Autowired
    private IPolicyUserService policyUserService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized int createPolicyInfoApplyMatter(PolicyInfoApplyMatterBo policyInfoApplyMatterBo) throws ArgumentErrorException {
        PolicyInfoApplyMatter policyInfoApplyMatter = new PolicyInfoApplyMatter();
        BeanUtils.copyProperties(policyInfoApplyMatterBo,policyInfoApplyMatter);
        //查询当前事项所在的主管部门
        PolicyInfoMatter matter = policyInfoMatterService.findPolicyInfoMatterById(policyInfoApplyMatter.getApplyMatterId());
        if(matter == null){
            throw new ArgumentErrorException("请在线申请相关政策!");
        }
        policyInfoApplyMatter.setCurrentAuditOrg(matter.getOrgId());
        policyInfoApplyMatter.setCurrentAuditNode(PolicyFulfillmentConstant.Matter_Audit_Node.SupervisorOrgEarlyAudit.value());
        policyInfoApplyMatter.setCurrentAuditTime(new Date());
        policyInfoApplyMatter.setApplyTime(new Date());
        policyInfoApplyMatter.setApplyNo(serialNumService.generateSerialNumberByModelCode("SX"));
        policyInfoApplyMatterRepository.createPolicyInfoApplyMatterSelective(policyInfoApplyMatter);
        //关联相关材料
        List<PolicyInfoApplyMaterialVo> policyInfoApplyMaterialVos = policyInfoApplyMatterBo.getPolicyInfoApplyMaterialVos();
        if(!CollectionUtil.isEmpty(policyInfoApplyMaterialVos)){
            List<PolicyInfoApplyMaterial> policyInfoApplyMaterials = BeansUtil.listCopy(policyInfoApplyMaterialVos, PolicyInfoApplyMaterial.class);
            if(!CollectionUtil.isEmpty(policyInfoApplyMaterials)){
                policyInfoApplyMaterials.forEach(policyInfoApplyMaterial -> {
                    policyInfoApplyMaterial.setApplyMatterId(policyInfoApplyMatter.getId());
                    applyMaterialRepository.createPolicyInfoApplyMaterialSelective(policyInfoApplyMaterial);
                });
            }
        }
        //向流程表插入一条数据
        PolicyInfoApproveProcess policyInfoApproveProcess = new PolicyInfoApproveProcess();
        policyInfoApproveProcess.setApplyMatterId(policyInfoApplyMatter.getId());
        policyInfoApproveProcess.setApprovePerson(policyInfoApplyMatter.getApplyCompanyId());
        policyInfoApproveProcess.setCurrentAuditStatus(PolicyFulfillmentConstant.Matter_Audit_Status.AuditPass.value());
        policyInfoApproveProcess.setApproveTime(policyInfoApplyMatter.getApplyTime());
        policyInfoApproveProcess.setCurrentProcessNode(PolicyFulfillmentConstant.Matter_Audit_Node.CompanyAudit.value());
        policyInfoApproveProcessRepository.createPolicyInfoApproveProcessSelective(policyInfoApproveProcess);
        //统计申请数量
        policyInfoMatterService.updateMatterDeclaredQuantityById(policyInfoApplyMatterBo.getApplyMatterId());
        return 1;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePolicyInfoApplyMatter(int id) {
         policyInfoApplyMatterRepository.deletePolicyInfoApplyMatterByPrimaryKey(id);
         applyMaterialRepository.deletePolicyInfoApplyMaterialByApplyMatterId(id);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updatePolicyInfoApplyMatter(PolicyInfoApplyMatter policyInfoApplyMatter) {
        return policyInfoApplyMatterRepository.updatePolicyInfoApplyMatterByPrimaryKeySelective(policyInfoApplyMatter);
    }


    @Override
    public PolicyInfoApplyMatterDetailVo findPolicyInfoApplyMatterById(int id) {
        PolicyInfoApplyMatterDetailVo result = new PolicyInfoApplyMatterDetailVo();
        PolicyInfoApplyMatter policyInfoApplyMatter = policyInfoApplyMatterRepository.searchPolicyInfoApplyMatterByPrimaryKey(id);
        if(policyInfoApplyMatter != null){
            BeanUtils.copyProperties(policyInfoApplyMatter,result);
            //查询事项名称
            PolicyInfoMatter matter = policyInfoMatterService.findPolicyInfoMatterById(policyInfoApplyMatter.getApplyMatterId());
            if(matter != null){
                result.setMatterTitle(matter.getTitle());
            }
            //查询企业名称
            PolicyCompanyUser policyCompanyUser = policyCompanyUserRepository.searchPolicyCompanyUserByPrimaryKey((int) policyInfoApplyMatter.getApplyCompanyId());
            if(policyCompanyUser != null){
                result.setCompanyName(policyCompanyUser.getCompanyName());
            }
            //查询附件信息
            List<PolicyInfoApplyMaterial> applyMaterials = applyMaterialRepository.findApplyMaterialsByApplyMatterId(policyInfoApplyMatter.getId());
            if(!CollectionUtil.isEmpty(applyMaterials )){
                List<PolicyInfoApplyMaterialVo> policyInfoApplyMaterialVos = BeansUtil.listCopy(applyMaterials, PolicyInfoApplyMaterialVo.class);
                if(!CollectionUtil.isEmpty(policyInfoApplyMaterialVos)){
                    result.setPolicyInfoApplyMaterialVos(policyInfoApplyMaterialVos);
                }
            }
            //查询审批流程
            List<PolicyAuditProcessVo> auditProcessVos = findAuditProcessByApplyMatterId(id);
            result.setPolicyAuditProcessVos(auditProcessVos);
        }
        return result;
    }

    @Override
    public PageResult findApprovalGroupInfo(PolicyInfoApplyMatterQueryCondition queryCondition) {
        PageHelper.startPage(queryCondition.getPage(), queryCondition.getSize());
        List<PolicyInfoApplyMatterVo> list = policyInfoApplyMatterRepository.findApprovalGroupInfo(queryCondition);
        PageInfo<PolicyInfoApplyMatterVo> pageInfo = new PageInfo<>(list);
        return new PageResult(queryCondition.getPage(), queryCondition.getSize(), (int) pageInfo.getTotal(), list);
    }

    @Override
    public PageResult findApprovalHistoryGroupInfo(PolicyInfoApplyMatterQueryCondition queryCondition) {
        PageHelper.startPage(queryCondition.getPage(), queryCondition.getSize());
        List<PolicyInfoApplyMatterVo> list = policyInfoApplyMatterRepository.findApprovalHistoryGroupInfo(queryCondition);
        PageInfo<PolicyInfoApplyMatterVo> pageInfo = new PageInfo<>(list);
        return new PageResult(queryCondition.getPage(), queryCondition.getSize(), (int) pageInfo.getTotal(), list);
    }

    @Override
    public PageResult findPolicyInfoApplyMatterByQueryCondition(PolicyInfoApplyMatterQueryCondition policyInfoApplyMatterQueryCondition) throws ArgumentErrorException {
        PageResult result = null;
        PolicyUser headerUser = myHeaderUtil.getHeaderUser();
        if(headerUser == null){
            throw new ArgumentErrorException("用户登录信息已过期，请重新登录！");
        }
        PolicyFulfillmentConstant.Role_Name roleNameEnum = PolicyFulfillmentConstant.Role_Name.byValue(headerUser.getRoleName());
        switch (roleNameEnum){
            case Admin:
                break;
            case Park:
                policyInfoApplyMatterQueryCondition.setAuditOrg(headerUser.getOrgId());
                break;
            case SupervisorOrg:
                policyInfoApplyMatterQueryCondition.setAuditOrg(headerUser.getOrgId());
                break;
            case PolicyEnforcementOfficeAudit:
                break;
            case Financial:
                break;
        }
        policyInfoApplyMatterQueryCondition.setCurrentUserOrgId(headerUser.getOrgId());
        policyInfoApplyMatterQueryCondition.setCurrentLoginId(headerUser.getId());
        List<PolicyInfoApplyMatterVo> policyInfoApplyMatterVos = new ArrayList<>();
        PageHelper.startPage(policyInfoApplyMatterQueryCondition.getPage(), policyInfoApplyMatterQueryCondition.getSize());
        if(PolicyFulfillmentConstant.Role_Name.Admin.value().equals(headerUser.getRoleName())
                || PolicyFulfillmentConstant.Role_Name.PolicyEnforcementOfficeAudit.value().equals(headerUser.getRoleName())
                || PolicyFulfillmentConstant.Role_Name.Financial.value().equals(headerUser.getRoleName())
        ){
            policyInfoApplyMatterVos = policyInfoApplyMatterRepository.
                    findPolicyInfoAllApplyMatterByQueryCondition(policyInfoApplyMatterQueryCondition);
        }else if(PolicyFulfillmentConstant.Role_Name.SupervisorOrg.value().equals(headerUser.getRoleName())){
            policyInfoApplyMatterVos = policyInfoApplyMatterRepository.
                    findPolicyInfoApplyMatterByQueryCondition(policyInfoApplyMatterQueryCondition);
        }else if(PolicyFulfillmentConstant.Role_Name.Park.value().equals(headerUser.getRoleName())){
            policyInfoApplyMatterVos = policyInfoApplyMatterRepository.
                    findPolicyInfoParkApplyMatterByQueryCondition(policyInfoApplyMatterQueryCondition);
        }

        if(!CollectionUtil.isEmpty(policyInfoApplyMatterVos)){
            policyInfoApplyMatterVos.forEach(policyInfoApplyMatterVo -> {
                //查询主管部门名称
                PolicyOrg policyOrg = policyOrgRepository.searchPolicyOrgByPrimaryKey(policyInfoApplyMatterVo.getOrgId());
                if(policyOrg != null){
                    policyInfoApplyMatterVo.setOrgName(policyOrg.getOrgName());
                }
                //查询归属园区名称
                PolicyOrg ownedPark = policyOrgRepository.searchPolicyOrgByPrimaryKey(policyInfoApplyMatterVo.getOwnedPark());
                if(ownedPark != null){
                    policyInfoApplyMatterVo.setOwnedParkName(ownedPark.getOrgName());
                }
                //计算下个审核节点i
                if(PolicyFulfillmentConstant.Matter_Audit_Node.Suspend.value().equals(policyInfoApplyMatterVo.getCurrentAuditNode()) ||
                        PolicyFulfillmentConstant.Matter_Audit_Node.Disbursed.value().equals(policyInfoApplyMatterVo.getCurrentAuditNode())){
                    policyInfoApplyMatterVo.setNextAuditNode(null);
                }else {
                    Integer nextAuditNode = Integer.valueOf(policyInfoApplyMatterVo.getCurrentAuditNode()) + 1;
                    policyInfoApplyMatterVo.setNextAuditNode(String.valueOf(nextAuditNode));
                }
                //计算剩余审核节点个数
                int remainingAuditNodeCount = 7 - Integer.valueOf(policyInfoApplyMatterVo.getCurrentAuditNode());
                if(remainingAuditNodeCount <= 0){
                    policyInfoApplyMatterVo.setRemainingAuditNodeCount(0);
                }else{
                    policyInfoApplyMatterVo.setRemainingAuditNodeCount(remainingAuditNodeCount);
                }
                //查询最后修改人名称
                if(policyInfoApplyMatterVo.getUpdatePerson() != null){
                    PolicyUser policyUser = policyUserService.findPolicyUserById(policyInfoApplyMatterVo.getUpdatePerson());
                    if(policyUser != null){
                        policyInfoApplyMatterVo.setUpdatePersonName(policyUser.getUserName());
                    }
                }
            });
            PageInfo<PolicyInfoApplyMatterVo> pageInfo = new PageInfo<>(policyInfoApplyMatterVos);
            result = new PageResult(policyInfoApplyMatterQueryCondition.getPage(), policyInfoApplyMatterQueryCondition.getSize(),
                    (int) pageInfo.getTotal(), policyInfoApplyMatterVos);
        }
        return result;
    }

    @Override
    public PageResult findApprovalHistory(PolicyInfoApplyMatterQueryCondition queryCondition) {
        PageHelper.startPage(queryCondition.getPage(), queryCondition.getSize());
        List<PolicyInfoApplyMatterVo> list = policyInfoApplyMatterRepository.findApprovalHistory(queryCondition);
        PageInfo<PolicyInfoApplyMatterVo> pageInfo = new PageInfo<>(list);
        return new PageResult(queryCondition.getPage(), queryCondition.getSize(), (int) pageInfo.getTotal(), list);
    }

    @Override
    public void urgeApplyMatter(int id) throws ArgumentErrorException {
        //查询当前登录人信息
        PolicyUser headerUser = myHeaderUtil.getHeaderUser();
        if(headerUser == null){
            throw new ArgumentErrorException("用户登录信息已过期，请重新登录！");
        }
        //判断当前事项的审核节点是什么节点  中止以及政策办材料审核不需要进行催办
        PolicyInfoApplyMatter policyInfoApplyMatter = policyInfoApplyMatterRepository.searchPolicyInfoApplyMatterByPrimaryKey(id);
        if(policyInfoApplyMatter == null){
            throw new ArgumentErrorException("请选择正在申请审批的事项进行催办！");
        }
        String currentAuditNode = policyInfoApplyMatter.getCurrentAuditNode();
        if(PolicyFulfillmentConstant.Matter_Audit_Node.Disbursed.value().equals(currentAuditNode) ||
                PolicyFulfillmentConstant.Matter_Audit_Node.Suspend.value().equals(currentAuditNode) ||
                PolicyFulfillmentConstant.Matter_Audit_Node.PolicyEnforcementOfficeAudit.value().equals(currentAuditNode)){
            throw new ArgumentErrorException("审核节点为已拨付/中止/政策办审核不能进行催办操作！");
        }
        //记录更新人
        policyInfoApplyMatter.setUpdatePerson(headerUser.getId());
        policyInfoApplyMatterRepository.updatePolicyInfoApplyMatterByPrimaryKey(policyInfoApplyMatter);
        //获取当前正在审核的部门
        int currentAuditOrg = policyInfoApplyMatter.getCurrentAuditOrg();
        //通过审核部门查询部门下所有人员，并通知其下所有人员
        List<PolicyUser> policyUsers = policyUserService.findPolicyUsersByOrgId(currentAuditOrg);
        if(!CollectionUtil.isEmpty(policyUsers)){
            //发送短信通知
//            for (PolicyUser policyUser : policyUsers) {
//                Map<String,String> map = new HashMap<>();
//                map.put("code", policyInfoApplyMatter.getApplyNo());
//                String templateCode = "SMS_223190177";
//                String templateParam = "{\"code\":\"" + policyInfoApplyMatter.getApplyNo() + "\"}";
//                try {
//                    SmsUtil.sendSms(policyUser.getPhone(), map, templateCode, templateParam);
//                } catch (Exception e) {
//                    throw new ArgumentErrorException("短信发送失败！");
//                }
//            }
        }
    }

    @Override
    public List<PolicyAuditProcessVo> findAuditProcessByApplyMatterId(int id) {
        List<PolicyAuditProcessVo> policyAuditProcessVos = new ArrayList<>();
        List<PolicyInfoApproveProcess> approveProcesses = policyInfoApproveProcessRepository.findAuditProcessByApplyMatterId(id);
        if(!CollectionUtil.isEmpty(approveProcesses)){
            policyAuditProcessVos = BeansUtil.listCopy(approveProcesses, PolicyAuditProcessVo.class);
            if(!CollectionUtil.isEmpty(policyAuditProcessVos)){
                policyAuditProcessVos.forEach(policyAuditProcessVo -> {
                    //查询审批人名称
                    if(PolicyFulfillmentConstant.Matter_Audit_Node.CompanyAudit.value().equals(policyAuditProcessVo.getCurrentProcessNode())){
                        PolicyCompanyUser policyCompanyUser = policyCompanyUserRepository.searchPolicyCompanyUserByPrimaryKey((int) policyAuditProcessVo.getApprovePerson());
                        if(policyCompanyUser != null){
                            policyAuditProcessVo.setApprovePersonName(policyCompanyUser.getCompanyName());
                        }
                    }else {
                        PolicyUser policyUser = policyUserService.findPolicyUserById(policyAuditProcessVo.getApprovePerson());
                        if(policyUser != null){
                            policyAuditProcessVo.setApprovePersonName(policyUser.getUserName());
                        }
                    }
                });
            }
        }
        return policyAuditProcessVos;
    }

    @Override
    public PageResult getPolicyInfoApplyMatterByCondition(PortalApplyMatterQueryCondition portalApplyMatterQueryCondition) {
        PageResult result = null;
        PageHelper.startPage(portalApplyMatterQueryCondition.getPage(), portalApplyMatterQueryCondition.getSize());
        List<PortalApplyMatterVo> portalApplyMatterVos = policyInfoApplyMatterRepository.getPolicyInfoApplyMatterByCondition(portalApplyMatterQueryCondition);
        if(!CollectionUtil.isEmpty(portalApplyMatterVos)){
            PageInfo<PortalApplyMatterVo> pageInfo = new PageInfo<>(portalApplyMatterVos);
            result = new PageResult(portalApplyMatterQueryCondition.getPage(), portalApplyMatterQueryCondition.getSize(),
                    (int) pageInfo.getTotal(), portalApplyMatterVos);
        }
        return result;
    }

    @Override
    public void auditMatter(AuditMatterBo auditMatterBo) throws ArgumentErrorException {
        //查询当前登录人信息
        PolicyUser headerUser = myHeaderUtil.getHeaderUser();
        if(headerUser == null){
            throw new ArgumentErrorException("用户登录信息已过期，请重新登录！");
        }
        if (auditMatterBo.getId() != null) {
            auditMatterOprater(auditMatterBo, headerUser);
        } else {
            auditMatterBo.getIds().forEach(id -> {
                auditMatterBo.setId(id);
                try {
                    auditMatterOprater(auditMatterBo, headerUser);
                } catch (ArgumentErrorException e) {
                    e.printStackTrace();
                }
            });
        }
    }

//    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditMatterOprater(AuditMatterBo auditMatterBo, PolicyUser headerUser) throws ArgumentErrorException {
        //查询当前
        PolicyInfoApplyMatter policyInfoApplyMatter = policyInfoApplyMatterRepository.searchPolicyInfoApplyMatterByPrimaryKey(auditMatterBo.getId());
        if(policyInfoApplyMatter == null){
            throw new ArgumentErrorException("请选择正在申请审批的事项进行审批操作！");
        }
        String currentAuditNode = policyInfoApplyMatter.getCurrentAuditNode();
        if(PolicyFulfillmentConstant.Matter_Audit_Node.Disbursed.value().equals(currentAuditNode)){
            throw new ArgumentErrorException("当前选择的申请审批已经拨付，不能进行审批操作！");
        }
        if(PolicyFulfillmentConstant.Matter_Audit_Node.Suspend.value().equals(currentAuditNode)){
            throw new ArgumentErrorException("当前选择的申请审批已中止，不能进行审批操作！");
        }
        if(PolicyFulfillmentConstant.CurrentAuditStatus.Locked.value().equals(policyInfoApplyMatter.getCurrentAuditStatus())){
            throw new ArgumentErrorException("当前选择的申请审批需要进行补充材料不能进行审批操作！");
        }
        if(PolicyFulfillmentConstant.Matter_Audit_Node.CompanyAudit.value().equals(currentAuditNode)){
            throw new ArgumentErrorException("当前选择的申请审批已经被主管部门驳回不能进行流程操作！");
        }
        if(!currentAuditNode.equals(auditMatterBo.getCurrentAuditNode())){
            throw new ArgumentErrorException("当前选择的申请审批已操作，请刷新页面！");
        }
        //权限控制
        if(PolicyFulfillmentConstant.Matter_Audit_Node.SupervisorOrgEarlyAudit.value().equals(currentAuditNode) &&
                !PolicyFulfillmentConstant.Role_Name.SupervisorOrg.value().equals(headerUser.getRoleName())){
            throw new ArgumentErrorException("主管部门初审必须由主管部门下的人员进行审核！");
        }else if(PolicyFulfillmentConstant.Matter_Audit_Node.PolicyEnforcementOfficeAudit.value().equals(currentAuditNode) &&
                !PolicyFulfillmentConstant.Role_Name.PolicyEnforcementOfficeAudit.value().equals(headerUser.getRoleName())){
            throw new ArgumentErrorException("政策办材料审核必须由政策办部门下的人员进行审核！");
        }else if(PolicyFulfillmentConstant.Matter_Audit_Node.SupervisorOrgReview.value().equals(currentAuditNode) &&
                !PolicyFulfillmentConstant.Role_Name.SupervisorOrg.value().equals(headerUser.getRoleName())){
            throw new ArgumentErrorException("主管部门复审必须由主管部门下的人员进行审核！");
        }else if(PolicyFulfillmentConstant.Matter_Audit_Node.ParkAudit.value().equals(currentAuditNode) &&
                !PolicyFulfillmentConstant.Role_Name.Park.value().equals(headerUser.getRoleName())){
            throw new ArgumentErrorException("园区终审必须由园区下的人员进行审核！");
        }else if(PolicyFulfillmentConstant.Matter_Audit_Node.FinancialAudit.value().equals(currentAuditNode) &&
                !PolicyFulfillmentConstant.Role_Name.Financial.value().equals(headerUser.getRoleName())){
            throw new ArgumentErrorException("财政审核必须由财政部门下的人员进行审核！");
        }else if(PolicyFulfillmentConstant.Matter_Audit_Node.ParkPublicityAppropriation.value().equals(currentAuditNode) &&
                !PolicyFulfillmentConstant.Role_Name.Park.value().equals(headerUser.getRoleName())){
            throw new ArgumentErrorException("园区公示拨付必须由园区下的人员进行审核！");
        }
        String status = auditMatterBo.getStatus();
        //审核状态
        PolicyFulfillmentConstant.Matter_Audit_Status matterAuditStatus = PolicyFulfillmentConstant.Matter_Audit_Status.byValue(status);
        //审核节点
        PolicyFulfillmentConstant.Matter_Audit_Node matterAuditNode = PolicyFulfillmentConstant.Matter_Audit_Node.byValue(currentAuditNode);
        policyInfoApplyMatter.setCurrentAuditTime(new Date());
        switch (matterAuditStatus){
            case AuditPass:
                auditPass(policyInfoApplyMatter,currentAuditNode,matterAuditNode);
                break;
            case Suspend:
                policyInfoApplyMatter.setCurrentAuditNode(PolicyFulfillmentConstant.Matter_Audit_Node.Suspend.value());
                break;
            case Dismissed:
                dismissed(policyInfoApplyMatter,currentAuditNode,matterAuditNode);
                break;
            case SupplementaryMaterials:
                policyInfoApplyMatter.setCurrentAuditStatus(PolicyFulfillmentConstant.CurrentAuditStatus.Locked.value());
                break;
        }
        //记录更新人
        policyInfoApplyMatter.setUpdatePerson(headerUser.getId());
        //记录审核人
        String auditPerson = null;
        if(StringUtil.isEmpty(policyInfoApplyMatter.getAuditPerson())){
            auditPerson = headerUser.getId().toString();
        }else {
            auditPerson = policyInfoApplyMatter.getAuditPerson() +";"+headerUser.getId();
        }
        policyInfoApplyMatter.setAuditPerson(auditPerson);
        //更新主表数据
        policyInfoApplyMatterRepository.updateApplyMatter(policyInfoApplyMatter);
        //创建旧流程数据到流程表
        PolicyInfoApproveProcess policyInfoApproveProcess = new PolicyInfoApproveProcess();
        policyInfoApproveProcess.setApplyMatterId(policyInfoApplyMatter.getId());
        policyInfoApproveProcess.setApprovePerson(headerUser.getId());
        policyInfoApproveProcess.setApproveOrg(headerUser.getOrgId());
        policyInfoApproveProcess.setApproveTime(new Date());
        policyInfoApproveProcess.setCurrentAuditStatus(status);
        policyInfoApproveProcess.setCurrentProcessNode(currentAuditNode);
        policyInfoApproveProcess.setApproveSuggestion(auditMatterBo.getApproveSuggestion());
        policyInfoApproveProcess.setSuggestedAmount(auditMatterBo.getSuggestedAmount());
        policyInfoApproveProcess.setTimeoutDesc(auditMatterBo.getTimeoutDesc());
        policyInfoApproveProcessRepository.createPolicyInfoApproveProcessSelective(policyInfoApproveProcess);
    }

    @Override
    public PageResult findLoginUserApplyMatterByCondition(LoginUserApplyMatterQueryCondition loginUserApplyMatterQueryCondition) {
        PageResult result = null;
        if(!StringUtil.isEmpty(loginUserApplyMatterQueryCondition.getApplyStatus())){
            PolicyFulfillmentConstant.DeclarationStatus declarationStatus = PolicyFulfillmentConstant.DeclarationStatus.
                    byValue(loginUserApplyMatterQueryCondition.getApplyStatus());
            switch (declarationStatus){
                case InProcess:
                    loginUserApplyMatterQueryCondition.setAuditNode(Arrays.asList("1","2","3","4","5","6"));
                    break;
                case Completed:
                    loginUserApplyMatterQueryCondition.setAuditNode(Arrays.asList("7"));
                    break;
                case Suspension:
                    loginUserApplyMatterQueryCondition.setAuditNode(Arrays.asList("8"));
                    break;
                case SupplementaryMaterials:
                    loginUserApplyMatterQueryCondition.setAuditStatus(PolicyFulfillmentConstant.CurrentAuditStatus.Locked.value());
                    break;
            }
        }
        PageHelper.startPage(loginUserApplyMatterQueryCondition.getPage(), loginUserApplyMatterQueryCondition.getSize());
        List<PersonalApplyMatterVo> personalApplyMatterVos = policyInfoApplyMatterRepository.findLoginUserApplyMatterByCondition(loginUserApplyMatterQueryCondition);
        if(!CollectionUtil.isEmpty(personalApplyMatterVos)){
            personalApplyMatterVos.forEach(personalApplyMatterVo -> {
                if(PolicyFulfillmentConstant.CurrentAuditStatus.Locked.value().equals(personalApplyMatterVo.getCurrentAuditStatus())){
                    personalApplyMatterVo.setApplyStatus(PolicyFulfillmentConstant.DeclarationStatus.SupplementaryMaterials.value());
                }else {
                    if(PolicyFulfillmentConstant.Matter_Audit_Node.Disbursed.value().equals(personalApplyMatterVo.getCurrentAuditNode())){
                        personalApplyMatterVo.setApplyStatus(PolicyFulfillmentConstant.DeclarationStatus.Completed.value());
                    }else if(PolicyFulfillmentConstant.Matter_Audit_Node.Suspend.value().equals(personalApplyMatterVo.getCurrentAuditNode())){
                        personalApplyMatterVo.setApplyStatus(PolicyFulfillmentConstant.DeclarationStatus.Suspension.value());
                    }else {
                        personalApplyMatterVo.setApplyStatus(PolicyFulfillmentConstant.DeclarationStatus.InProcess.value());
                    }
                }
            });
            PageInfo<PersonalApplyMatterVo> pageInfo = new PageInfo<>(personalApplyMatterVos);
            result = new PageResult(loginUserApplyMatterQueryCondition.getPage(), loginUserApplyMatterQueryCondition.getSize(),
                    (int) pageInfo.getTotal(), personalApplyMatterVos);
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void supplementaryMaterials(SupplementaryMaterials supplementaryMaterials) throws ArgumentErrorException {
        PolicyInfoApplyMatter policyInfoApplyMatter = policyInfoApplyMatterRepository.searchPolicyInfoApplyMatterByPrimaryKey(Math.toIntExact(supplementaryMaterials.getApplyId()));
        List<PolicyInfoApplyMaterialVo> policyInfoApplyMaterialVos = supplementaryMaterials.getPolicyInfoApplyMaterialVos();
        if(!CollectionUtil.isEmpty(policyInfoApplyMaterialVos)){
            List<PolicyInfoApplyMaterial> policyInfoApplyMaterials = BeansUtil.listCopy(policyInfoApplyMaterialVos, PolicyInfoApplyMaterial.class);
            if(!CollectionUtil.isEmpty(policyInfoApplyMaterials)){
                policyInfoApplyMaterials.forEach(policyInfoApplyMaterial -> {
                    policyInfoApplyMaterial.setApplyMatterId(supplementaryMaterials.getApplyId());
                    applyMaterialRepository.createPolicyInfoApplyMaterialSelective(policyInfoApplyMaterial);
                });
            }
        }else {
            throw new ArgumentErrorException("请补充相关材料！");
        }
        policyInfoApplyMatterRepository.updateCurrentAuditStatus(supplementaryMaterials.getApplyId());
        policyInfoApproveProcessRepository.updatePolicyInfoApproveStatus(policyInfoApplyMatter.getId(),policyInfoApplyMatter.getCurrentAuditNode());
    }

    private void dismissed(PolicyInfoApplyMatter policyInfoApplyMatter, String currentAuditNode, PolicyFulfillmentConstant.Matter_Audit_Node matterAuditNode) {
        //驳回操作 返回上个审核节点 目前返回到对面部门
        int nextAuditNode = Integer.valueOf(currentAuditNode) - 1;
        policyInfoApplyMatter.setCurrentAuditNode(String.valueOf(nextAuditNode));
        PolicyInfoMatter policyInfoMatter = policyInfoMatterService.findPolicyInfoMatterById(policyInfoApplyMatter.getApplyMatterId());
        switch (matterAuditNode){
            case ParkAudit:
                //园区驳回 返回上个部门审核 审核节点为 主管部门复审 审核部门为主管部门
                if (policyInfoMatter != null) {
                    policyInfoApplyMatter.setCurrentAuditOrg(policyInfoMatter.getOrgId());
                }
                break;
            case PolicyEnforcementOfficeAudit:
                //政策办驳回 返回上个部门审核 审核节点为 主管部门初审 审核部门为主管部门
                if (policyInfoMatter != null) {
                    policyInfoApplyMatter.setCurrentAuditOrg(policyInfoMatter.getOrgId());
                }
                break;
            case SupervisorOrgEarlyAudit:
                //主管部门初审 驳回 返回上个部门审核 审核节点为 企业在线申请 审核部门为还是为当前部门
                break;
            case SupervisorOrgReview:
                //主管部门复审  驳回 返回上个部门审核 审核节点为 政策办审核  审核部门为政策兑现办
                List<PolicyOrg> policyOrgs = policyOrgRepository.findPolicyOrgsByOrgType(PolicyFulfillmentConstant.OrgType.PolicyOffice.value());
                if(!CollectionUtil.isEmpty(policyOrgs)){
                    policyInfoApplyMatter.setCurrentAuditOrg(policyOrgs.get(0).getId());
                }
                break;
            case FinancialAudit:
                //财政审核  驳回 返回上个部门审核 审核节点为 园区终审  审核部门为园区
                PolicyCompanyUser policyCompanyUser1 = policyCompanyUserRepository.searchPolicyCompanyUserByPrimaryKey((int) policyInfoApplyMatter.getApplyCompanyId());
                if(policyCompanyUser1 != null){
                    policyInfoApplyMatter.setCurrentAuditOrg(policyCompanyUser1.getOrgId());
                }
                break;
            case ParkPublicityAppropriation:
                //园区公示拨付
                break;
        }
    }

    //审核通过方法
    private void auditPass(PolicyInfoApplyMatter policyInfoApplyMatter, String currentAuditNode,
                           PolicyFulfillmentConstant.Matter_Audit_Node matterAuditNode) {
        //审核通过 进入下个流程
        int nextAuditNode = Integer.valueOf(currentAuditNode) + 1;
        policyInfoApplyMatter.setCurrentAuditNode(String.valueOf(nextAuditNode));
        switch (matterAuditNode){
            case ParkPublicityAppropriation:
                //园区公示拨付通过 流程结束  没有下个节点  审核部门还是当前部门
                //policyInfoApplyMatter.setCurrentAuditOrg(null);
                break;
            case PolicyEnforcementOfficeAudit:
                //政策办审核通过 流向下个审核节点  主管部门复审 设置下个节点审核部门为主管部门
                PolicyInfoMatter policyInfoMatter = policyInfoMatterService.findPolicyInfoMatterById(policyInfoApplyMatter.getApplyMatterId());
                if (policyInfoMatter != null) {
                    policyInfoApplyMatter.setCurrentAuditOrg(policyInfoMatter.getOrgId());
                }
                break;
            case SupervisorOrgEarlyAudit:
                //主管部门初审 流向下个审核节点 政策办审核 审核通过设置下个审核节点审核部门为政策办
                //查询政策办组织
                List<PolicyOrg> policyOrgs = policyOrgRepository.findPolicyOrgsByOrgType(PolicyFulfillmentConstant.OrgType.PolicyOffice.value());
                if(!CollectionUtil.isEmpty(policyOrgs)){
                    policyInfoApplyMatter.setCurrentAuditOrg(policyOrgs.get(0).getId());
                }
                break;
            case SupervisorOrgReview:
                //主管部门复审 流向下个审核节点 园区终核  审核通过设置下个审核节点部门为园区
                PolicyCompanyUser policyCompanyUser = policyCompanyUserRepository.searchPolicyCompanyUserByPrimaryKey((int) policyInfoApplyMatter.getApplyCompanyId());
                if(policyCompanyUser != null){
                    policyInfoApplyMatter.setCurrentAuditOrg(policyCompanyUser.getOrgId());
                }
                break;
            case ParkAudit:
                //园区终核 流向下个审核节点 财政审核  审核通过设置下个审核节点部门为财政部门
                List<PolicyOrg> policyOrgList = policyOrgRepository.findPolicyOrgsByOrgType(PolicyFulfillmentConstant.OrgType.Financial.value());
                if(!CollectionUtil.isEmpty(policyOrgList)){
                    policyInfoApplyMatter.setCurrentAuditOrg(policyOrgList.get(0).getId());
                }
                break;
            case FinancialAudit:
                //财政审核 流向下个审核节点 园区公示拨付  审核通过设置下个审核节点部门为园区
                PolicyCompanyUser policyCompanyUser1 = policyCompanyUserRepository.searchPolicyCompanyUserByPrimaryKey((int) policyInfoApplyMatter.getApplyCompanyId());
                if(policyCompanyUser1 != null){
                    policyInfoApplyMatter.setCurrentAuditOrg(policyCompanyUser1.getOrgId());
                }
                break;
        }
    }


}
